package api

import (
	"TaskAssignmentSystem/pkg/utils"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
	"github.com/kataras/iris/v12"
	"net/http"
)

// //Policy allows not to be configured
// var stsPolicy string
//
// // you can modify the value according to the actual situation
var stsSession = "task-assignment-cloud"

// @Summary 获取STSToken
// @Description get oss sts token
// @Tags STS
// @Accept application/json
// @Produce application/json
// @param Accept-Version header  string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /app/oss/sts [post]
func GetSts(ctx iris.Context) {
	client, err := sts.NewClientWithAccessKey("cn-beijing", utils.ServerConf.AliOssConf.StsAccessKeyID, utils.ServerConf.AliOssConf.StsAccessKeySecret)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusGatewayTimeout, Message: err.Error()})
		return
	}
	//构建请求对象。
	request := sts.CreateAssumeRoleRequest()
	request.Scheme = "https"
	//设置参数。关于参数含义和设置方法，请参见API参考。
	request.RoleArn = utils.ServerConf.AliOssConf.RoleArn
	request.Domain = ""
	request.RoleSessionName = stsSession
	//发起请求，并得到响应。
	response, err := client.AssumeRole(request)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	ctx.JSON(iris.Map{"code": http.StatusOK, "message": "ok", "data": iris.Map{
		"accessKeyId":     response.Credentials.AccessKeyId,
		"accessKeySecret": response.Credentials.AccessKeySecret,
		"stsToken":        response.Credentials.SecurityToken, "endPoint": utils.ServerConf.AliOssConf.EndPoint,
		"bucket": utils.ServerConf.AliOssConf.Bucket,
	}})
	return
}
